package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.colorpicker.lib.ColorPicker;
import com.vilyever.drawingview.brush.drawing.PenBrush;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.adapter.TextColorAdapter;
import flc.ast.bean.MyColorBean;
import flc.ast.databinding.ActivityDrawBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class DrawActivity extends BaseAc<ActivityDrawBinding> {

    public static int kind = 0;//1模板 2比例画布 3相册图片
    public static int selImg;//模板
    public static int bili;//比例
    public static String imgPath = "";//图片
    private PenBrush penBrush;
    private int paintWidth = 15;//画笔宽度
    private int eraserWidth = 15;//橡皮擦宽度
    private ColorAdapter brushAdapter;
    private int oldBrushPos = 1;
    private ColorAdapter bgAdapter;
    private int oldBgPos = 1;
    private TextColorAdapter textAdapter;
    private int oldTextPos = 1;
    private Dialog myClearDialog;
    private List<String> listFile = new ArrayList<>();
    private Bitmap saveBitmap;
    private ColorPicker mColorPicker;
    private int style = 0;

    @Override
    protected int onCreate() {
        return R.layout.activity_draw;
    }

    @Override
    protected void initView() {
        mDataBinding.ivDrawBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivDrawSave.setOnClickListener(this);
        mDataBinding.ivDrawLast.setOnClickListener(this);
        mDataBinding.ivDrawNext.setOnClickListener(this);
        mDataBinding.ivDrawClear.setOnClickListener(this);
        mDataBinding.llDrawBrush.setOnClickListener(this);
        mDataBinding.llDrawColor.setOnClickListener(this);
        mDataBinding.llDrawEraser.setOnClickListener(this);
        mDataBinding.llDrawText.setOnClickListener(this);
        mDataBinding.llDrawBg.setOnClickListener(this);
        //画笔颜色
        mDataBinding.rvBrushColorList.setLayoutManager(new GridLayoutManager(mContext, 7));
        brushAdapter = new ColorAdapter();
        mDataBinding.rvBrushColorList.setAdapter(brushAdapter);
        brushAdapter.setOnItemClickListener(this);
        //文字颜色
        mDataBinding.rvTextColorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        textAdapter = new TextColorAdapter();
        mDataBinding.rvTextColorList.setAdapter(textAdapter);
        textAdapter.setOnItemClickListener(this);
        //画板背景颜色
        mDataBinding.rvBrushBgList.setLayoutManager(new GridLayoutManager(mContext, 7));
        bgAdapter = new ColorAdapter();
        mDataBinding.rvBrushBgList.setAdapter(bgAdapter);
        bgAdapter.setOnItemClickListener(this);
        //清空弹框
        clearDialog();
        //颜色选择器
        showColorPicker();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivDrawSave://保存
                saveImg();
                break;
            case R.id.ivDrawLast://上一步
                undo();
                break;
            case R.id.ivDrawNext://下一步
                redo();
                break;
            case R.id.ivDrawClear://清空画布
                myClearDialog.show();
                break;
            case R.id.llDrawBrush://画笔大小
                clearView();
                mDataBinding.tvDrawBrush.setTextColor(Color.BLACK);
                mDataBinding.ivDrawBrushLine.setVisibility(View.VISIBLE);
                mDataBinding.sbBrushSize.setVisibility(View.VISIBLE);
                break;
            case R.id.llDrawColor://画笔颜色
                clearView();
                mDataBinding.tvDrawColor.setTextColor(Color.BLACK);
                mDataBinding.ivDrawColorLine.setVisibility(View.VISIBLE);
                mDataBinding.rvBrushColorList.setVisibility(View.VISIBLE);
                break;
            case R.id.llDrawEraser://橡皮擦
                clearView();
                mDataBinding.tvDrawEraser.setTextColor(Color.BLACK);
                mDataBinding.ivDrawEraserLine.setVisibility(View.VISIBLE);
                mDataBinding.sbEraserSize.setVisibility(View.VISIBLE);
                penBrush.setIsEraser(true);
                break;
            case R.id.llDrawText://文字
                clearView();
                mDataBinding.tvDrawText.setTextColor(Color.BLACK);
                mDataBinding.ivDrawTextLine.setVisibility(View.VISIBLE);
                mDataBinding.llDrawTextView.setVisibility(View.VISIBLE);
                break;
            case R.id.llDrawBg://背景
                clearView();
                mDataBinding.tvDrawBg.setTextColor(Color.BLACK);
                mDataBinding.ivDrawBgLine.setVisibility(View.VISIBLE);
                mDataBinding.rvBrushBgList.setVisibility(View.VISIBLE);
                break;
            //清空弹框
            case R.id.ivDialogClearCancel://取消
                myClearDialog.dismiss();
                break;
            case R.id.ivDialogClearRight://确定
                myClearDialog.dismiss();
                mDataBinding.myDrawingView.clear();
                isReDoUndo();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == brushAdapter) {
            if (position == 0) {
                style = 1;
                mColorPicker.show();
            } else {
                brushAdapter.getItem(oldBrushPos).setSelect(false);
                brushAdapter.notifyItemChanged(oldBrushPos);
                oldBrushPos = position;
                brushAdapter.getItem(position).setSelect(true);
                brushAdapter.notifyItemChanged(position);
                penBrush.setColor(Color.parseColor(brushAdapter.getItem(position).getColor()));
            }
        } else if (adapter == textAdapter) {
            if (position == 0) {
                style = 2;
                mColorPicker.show();
            } else {
                textAdapter.getItem(oldTextPos).setSelect(false);
                textAdapter.notifyItemChanged(oldTextPos);
                oldTextPos = position;
                textAdapter.getItem(position).setSelect(true);
                textAdapter.notifyItemChanged(position);
                mDataBinding.txtStickerView.setTextColor(Color.parseColor(textAdapter.getItem(position).getColor()));
            }
        } else if (adapter == bgAdapter) {
            if (position == 0) {
                style = 3;
                mColorPicker.show();
            } else {
                bgAdapter.getItem(oldBgPos).setSelect(false);
                bgAdapter.notifyItemChanged(oldBgPos);
                oldBgPos = position;
                bgAdapter.getItem(position).setSelect(true);
                bgAdapter.notifyItemChanged(position);
                mDataBinding.rlDrawSaveView.setBackgroundColor(Color.parseColor(bgAdapter.getItem(position).getColor()));
                if (kind != 2) {
                    mDataBinding.rlDrawBgView.setBackgroundColor(Color.parseColor(bgAdapter.getItem(position).getColor()));
                }
            }
        }
    }

    @Override
    protected void initData() {
        setDrawImg();
        initPen();
        //画笔/文字颜色
        List<MyColorBean> listColor1 = new ArrayList<>();
        listColor1.add(new MyColorBean("", false));
        listColor1.add(new MyColorBean("#333333", true));
        listColor1.add(new MyColorBean("#F44236", false));
        listColor1.add(new MyColorBean("#FB6400", false));
        listColor1.add(new MyColorBean("#F7B501", false));
        listColor1.add(new MyColorBean("#6ED400", false));
        listColor1.add(new MyColorBean("#44D7B5", false));
        listColor1.add(new MyColorBean("#54B7F8", false));
        listColor1.add(new MyColorBean("#4DD0E2", false));
        listColor1.add(new MyColorBean("#4CB6AC", false));
        listColor1.add(new MyColorBean("#80C783", false));
        listColor1.add(new MyColorBean("#AED582", false));
        listColor1.add(new MyColorBean("#DDE775", false));
        listColor1.add(new MyColorBean("#FFF176", false));
        brushAdapter.setList(listColor1);
        List<MyColorBean> listColor2 = new ArrayList<>();
        listColor2.add(new MyColorBean("", false));
        listColor2.add(new MyColorBean("#333333", true));
        listColor2.add(new MyColorBean("#F44236", false));
        listColor2.add(new MyColorBean("#FB6400", false));
        listColor2.add(new MyColorBean("#F7B501", false));
        listColor2.add(new MyColorBean("#6ED400", false));
        listColor2.add(new MyColorBean("#44D7B5", false));
        listColor2.add(new MyColorBean("#54B7F8", false));
        listColor2.add(new MyColorBean("#4DD0E2", false));
        listColor2.add(new MyColorBean("#4CB6AC", false));
        listColor2.add(new MyColorBean("#80C783", false));
        listColor2.add(new MyColorBean("#AED582", false));
        listColor2.add(new MyColorBean("#DDE775", false));
        listColor2.add(new MyColorBean("#FFF176", false));
        textAdapter.setList(listColor2);
        //背景颜色
        List<MyColorBean> listBg = new ArrayList<>();
        listBg.add(new MyColorBean("", false));
        listBg.add(new MyColorBean("#FFFFFF", true));
        listBg.add(new MyColorBean("#FFCDD2", false));
        listBg.add(new MyColorBean("#E1BEE8", false));
        listBg.add(new MyColorBean("#C4C9E9", false));
        listBg.add(new MyColorBean("#B9DAF9", false));
        listBg.add(new MyColorBean("#B3E5FC", false));
        listBg.add(new MyColorBean("#B2EBF2", false));
        listBg.add(new MyColorBean("#B2DFDC", false));
        listBg.add(new MyColorBean("#C8E6CA", false));
        listBg.add(new MyColorBean("#DDEDC8", false));
        listBg.add(new MyColorBean("#FCEFBA", false));
        listBg.add(new MyColorBean("#FFE0B2", false));
        listBg.add(new MyColorBean("#E0E0E0", false));
        bgAdapter.setList(listBg);
        //文字输入监听
        mDataBinding.etDrawText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = mDataBinding.etDrawText.getText().toString();
                mDataBinding.txtStickerView.setText(text);
            }
        });
        //默认文字黑色
        mDataBinding.txtStickerView.setTextColor(Color.parseColor("#333333"));
        //监听绘画状态
        mDataBinding.myDrawingView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN://按下

                        break;
                    case MotionEvent.ACTION_UP://抬起
                        isReDoUndo();
                        break;
                }
                return false;
            }
        });
    }

    //设置画布大小图片
    private void setDrawImg() {
        int leftAndRight = 0;
        int topAndBottom = 0;
        switch (kind) {
            case 1:
                Glide.with(mContext).load(selImg).into(mDataBinding.ivDrawImg);
                break;
            case 2:
                switch (bili) {
                    case 1://9：16
                        leftAndRight = 200;
                        break;
                    case 2://3：4
                        leftAndRight = 150;
                        topAndBottom = 50;
                        break;
                    case 3://1：1
                        leftAndRight = 100;
                        topAndBottom = 100;
                        break;
                    case 4://16：9
                        topAndBottom = 150;
                        break;
                    case 5://4：3
                        leftAndRight = 50;
                        topAndBottom = 150;
                        break;
                    case 6://屏幕
                        break;
                }
                break;
            case 3:
                Glide.with(mContext).load(imgPath).into(mDataBinding.ivDrawImg);
                break;
        }
        setBili(leftAndRight, topAndBottom);
    }

    //设置画布比例
    private void setBili(int leftAndRight, int topAdnBottom) {
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(leftAndRight, topAdnBottom, leftAndRight, topAdnBottom + 200);//4个参数按顺序分别是左上右下
        mDataBinding.rlDrawSaveView.setLayoutParams(layoutParams);
    }

    //初始化画笔
    private void initPen() {
        penBrush = PenBrush.defaultBrush();
        penBrush.setColor(Color.parseColor("#333333"));//默认画笔颜色
        penBrush.setSize(15);//默认画笔大小
        mDataBinding.myDrawingView.setBrush(penBrush);
        //设置画笔大小&橡皮擦大小
        mDataBinding.sbBrushSize.setMax(50);
        mDataBinding.sbBrushSize.setProgress(5);
        mDataBinding.sbBrushSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                paintWidth = 5 + i * 2;
                penBrush.setSize(paintWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mDataBinding.sbEraserSize.setMax(50);
        mDataBinding.sbEraserSize.setProgress(5);
        mDataBinding.sbEraserSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //橡皮擦大小
                eraserWidth = 5 + i * 2;
                penBrush.setSize(eraserWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    //显示颜色选择器
    private void showColorPicker() {
        mColorPicker = new ColorPicker(this);
        mColorPicker.setListener(pickedColor -> {
            switch (style) {
                case 1://画笔颜色
                    brushAdapter.getItem(oldBrushPos).setSelect(false);
                    brushAdapter.notifyItemChanged(oldBrushPos);
                    oldBrushPos = 0;
                    brushAdapter.getItem(0).setSelect(true);
                    brushAdapter.notifyItemChanged(0);
                    penBrush.setColor(Color.parseColor(ColorUtils.int2RgbString(pickedColor)));
                    break;
                case 2://文字颜色
                    textAdapter.getItem(oldTextPos).setSelect(false);
                    textAdapter.notifyItemChanged(oldTextPos);
                    oldTextPos = 0;
                    textAdapter.getItem(0).setSelect(true);
                    textAdapter.notifyItemChanged(0);
                    mDataBinding.txtStickerView.setTextColor(Color.parseColor(ColorUtils.int2RgbString(pickedColor)));
                    break;
                case 3://背景颜色
                    bgAdapter.getItem(oldBgPos).setSelect(false);
                    bgAdapter.notifyItemChanged(oldBgPos);
                    oldBgPos = 0;
                    bgAdapter.getItem(0).setSelect(true);
                    bgAdapter.notifyItemChanged(0);
                    mDataBinding.rlDrawSaveView.setBackgroundColor(Color.parseColor(ColorUtils.int2RgbString(pickedColor)));
                    if (kind != 2) {
                        mDataBinding.rlDrawBgView.setBackgroundColor(Color.parseColor(ColorUtils.int2RgbString(pickedColor)));
                    }
                    break;
            }
        });
    }

    //保存到首页记录
    private void saveImg() {
        showDialog(getString(R.string.save_ing));
        mDataBinding.txtStickerView.setShowHelpBox(false);
        mDataBinding.ivDrawImg.setVisibility(View.GONE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<Bitmap>() {

                    @Override
                    public void doBackground(ObservableEmitter<Bitmap> emitter) {
                        Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.rlDrawSaveView);
                        //保存到记录
                        String resultFile = FileUtil.generateFilePath(Content.myDraw, ".png");
                        ImageUtils.save(bitmap, resultFile, Bitmap.CompressFormat.PNG);
                        //保存到相册
                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        emitter.onNext(bitmap);
                    }

                    @Override
                    public void accept(Bitmap bitmap) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_to_album);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 500);
    }

    //下一步
    private void redo() {
        if (mDataBinding.myDrawingView.canRedo()) {
            mDataBinding.myDrawingView.redo();
        }
        isReDoUndo();
    }

    //上一步
    private void undo() {
        if (mDataBinding.myDrawingView.canUndo()) {
            mDataBinding.myDrawingView.undo();
        }
        isReDoUndo();
    }

    //判断是否可以后退，前进
    private void isReDoUndo() {
        if (mDataBinding.myDrawingView.canUndo()) {
            mDataBinding.ivDrawLast.setImageResource(R.drawable.icon_ch1);
        } else {
            mDataBinding.ivDrawLast.setImageResource(R.drawable.icon_ch1a);
        }
        if (mDataBinding.myDrawingView.canRedo()) {
            mDataBinding.ivDrawNext.setImageResource(R.drawable.icon_ch2);
        } else {
            mDataBinding.ivDrawNext.setImageResource(R.drawable.icon_ch2a);
        }
    }

    //管理画笔样式
    private void clearView() {
        mDataBinding.tvDrawBrush.setTextColor(Color.parseColor("#80457096"));
        mDataBinding.tvDrawColor.setTextColor(Color.parseColor("#80457096"));
        mDataBinding.tvDrawEraser.setTextColor(Color.parseColor("#80457096"));
        mDataBinding.tvDrawText.setTextColor(Color.parseColor("#80457096"));
        mDataBinding.tvDrawBg.setTextColor(Color.parseColor("#80457096"));
        mDataBinding.ivDrawBrushLine.setVisibility(View.INVISIBLE);
        mDataBinding.ivDrawColorLine.setVisibility(View.INVISIBLE);
        mDataBinding.ivDrawEraserLine.setVisibility(View.INVISIBLE);
        mDataBinding.ivDrawTextLine.setVisibility(View.INVISIBLE);
        mDataBinding.ivDrawBgLine.setVisibility(View.INVISIBLE);
        penBrush.setIsEraser(false);
        mDataBinding.sbBrushSize.setVisibility(View.GONE);
        mDataBinding.rvBrushColorList.setVisibility(View.GONE);
        mDataBinding.sbEraserSize.setVisibility(View.GONE);
        mDataBinding.llDrawTextView.setVisibility(View.GONE);
        mDataBinding.rvBrushBgList.setVisibility(View.GONE);
    }

    //清空弹框
    private void clearDialog() {
        myClearDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_clear, null);
        myClearDialog.setContentView(inflate);
        myClearDialog.setCancelable(false);
        Window dialogWindow = myClearDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogClearCancel);
        ImageView dialogRight = inflate.findViewById(R.id.ivDialogClearRight);
        TextView dialogText = inflate.findViewById(R.id.tvDialogClearText);
        dialogText.setText(R.string.dialog_clear_text1);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
    }

}